<template>
    <div class="image-upload-component" v-if="!multiple">
       <!-- 单张图片上传 -->
      <el-upload class="image-uploader" :action="uploadActionUrl" :data="ossParams" :show-file-list="false" list-type="picture" :on-success="handleSuccess" :before-upload="beforeUpload" :on-change="handleChange">
        <img v-if="singleImageUrl" :src="singleImageUrl" class="image">
        <i v-else class="el-icon-plus image-uploader-icon"></i>
      </el-upload>
    </div>
  <div class="image-upload-component" v-else>
     <div style="position:relative;"  v-for="(item,index) in imageUrlList"  :key="item">
       <img :src="item" class="image" />
       <i class="el-icon el-icon-circle-close" style="position:absolute;top: 0;right: 0;font-size: 28px;z-index: 9;cursor:pointer;" @click="handleDelete(index)"></i>
     </div>
      <el-upload class="image-uploader" :action="uploadActionUrl" :data="ossParams" :show-file-list="false" list-type="picture" :on-success="handleSuccessMultiple" :before-upload="beforeUpload" :on-change="handleChange">
        <i class="el-icon-plus image-uploader-icon"></i>
      </el-upload>
  </div>
</template>

<script>
export default {
  name: 'image-upload',
  data() {
    return {
      uploadActionUrl: '',
      ossParams: { // OSS 上传附带参数
        key: '',
        dir: '',
        policy: '',
        OSSAccessKeyId: '',
        success_action_status: '',
        callback: '',
        signature: '',
      },
      singleImageUrl: '', // 单张图片
      imageUrlList: [], // 多张图片
    };
  },
  props: {
    uploadParams: { // 上传参数
      type: String,
      default: '',
    },
    multiple: { // 是否多张上传
      type: Boolean,
      default: false,
    },
    datalist: { // 多张图片列表
      type: Array,
      default: () => [],
    },
    imgUrl: { // 单张图片
      type: String,
      default: '',
    },
  },
  methods: {
    beforeUpload(file) {
      let upload = true;

      const isAllowFile = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg';
      const isAllowMsg = '只能上传png、jpg格式图片！';
      const isLimitSize = file.size / 1024 / 1024 < 10; // 限制最大10M
      if (!isAllowFile) {
        upload = false;
        this.$util.message(isAllowMsg);
      }

      if (!isLimitSize) {
        upload = false;
        this.$util.message('只能上传大小不能超过10MB的图片！');
      }
      return upload;
    },
    handleDelete(index) {
      if (!this.multiple) {
        this.singleImageUrl = '';
        this.$emit('change', this.singleImageUrl);
      } else {
        this.imageUrlList.splice(index, 1);
        this.$emit('change', this.imageUrlList);
      }
    },
    handleChange(file) {
      const randomName = this.randomFilename(file.name);
      this.ossParams.key = this.ossParams.dir + randomName;
    },
    handleSuccess(response, file, fileList) { // 上传成功
      console.log('上传成功', response);
      if (!this.multiple) {
        this.singleImageUrl = response.data.filename;
        this.$emit('change', this.singleImageUrl);
      }
    },
    handleSuccessMultiple(response, file, fileList) { // 上传成功
      this.imageUrlList.push(response.data.filename);
      this.$emit('change', this.imageUrlList);
    },
    randomString(len) { // 生成随机字符串
      const myDate = new Date();
      const seconds = myDate.getTime();
      len = len || 32;
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';

      const maxPos = chars.length;
      let pwd = '';
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }

      return seconds + pwd;
    },
    randomFilename(filename) { // 随机生成文件名
      const suffix = this.getSuffix(filename);
      const random_filename = this.randomString(10) + suffix;
      return random_filename;
    },
    getSuffix(filename) { // 获取文件后缀
      const pos = filename.lastIndexOf('.');
      let suffix = '';
      if (pos != -1) {
        suffix = filename.substring(pos);
      }
      return suffix;
    },
    setUploadParams(data) {
      this.uploadActionUrl = data.host;
      this.ossParams.dir = data.dir;
      this.ossParams.policy = data.policy;
      this.ossParams.OSSAccessKeyId = data.accessid;
      this.ossParams.success_action_status = '200'; // 让服务端返回200,不然，默认会返回204
      this.ossParams.callback = data.callback;
      this.ossParams.signature = data.signature;
    },
    init() {
      if (!this.multiple) {
        this.singleImageUrl = this.imgUrl || '';
      }
    },
  },
  watch: {
    uploadParams(val) {
      if (val) this.setUploadParams(JSON.parse(val));
    },
    imgUrl(val) {
      if (val && !this.multiple) {
        this.singleImageUrl = val;
      }
    },
  },
  mounted() {
    if (!this.uploadActionUrl && this.uploadParams) {
      this.setUploadParams(JSON.parse(this.uploadParams));
    }
    this.init();
  },
};
</script>

<style lang="scss">
.image-upload-component {
  display: flex;
  flex-wrap: wrap;
  .image {
    width: 178px;
    height: 178px;
    margin-right: 6px;
    margin-bottom: 6px;
    display: block;
    border: 1px dashed #d9d9d9;
  }
    .image-uploader {
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            &:hover {
                :hover {
                    border-color: #006DB8;
                }
            }
        }
        .image-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .image {
            width: 178px;
            height: 178px;
            display: block;
        }
    }
}
</style>
